package src.backtracking_algorithm;

import javax.swing.tree.TreeNode;
import java.awt.image.renderable.RenderableImage;

/**
 * @author starsea
 * @date 2024-08-11 16:19
 */

public class Test02 {
    static class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        public TreeNode(int val) {
            this.val = val;
        }
    }

    //计算布尔二叉树
    public boolean evaluateTree(TreeNode root) {
        if (root.left == null || root.right == null) {
            return root.val == 0 ? false : true;
        }
        return root.val == 2 ?
                evaluateTree(root.left) | evaluateTree(root.right) :
                evaluateTree(root.left) & evaluateTree(root.right);
    }

    //求根节点到叶节点数字之和
    public int sumNumbers(TreeNode root) {
        if (root == null) {
            return 0;
        }
        if (root.left == null && root.right == null) {
            return root.val;
        }
        return dfs(root, 0);

    }

    public int dfs(TreeNode root, int preSum) {
        preSum = preSum * 10 + root.val;
        if (root.left == null && root.right == null) {
            return preSum;
        }
        int right = 0;
        int left = 0;
        if (root.left != null) {
            right = dfs(root.left, preSum);
        }
        if (root.right != null) {
            left = dfs(root.right, preSum);
        }
        return left + right;
    }

    //二叉树减枝
    public TreeNode pruneTree(TreeNode root) {
        if (root == null) {
            return null;
        }
        root.left = pruneTree(root.left);
        root.right = pruneTree(root.right);
        if (root.left == null && root.right == null && root.val == 0) {
            return null;
        }
        return root;
    }
    //验证有效的二叉搜索树
    //public boolean isValidBST(TreeNode root) {
    //
    //
    //}

}
